import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

export const ORG_TYPE_OPTIONS = [
  { label: "卖家", value: "seller" },
  { label: "买家", value: "buyer" },
  { label: "买卖一体", value: "both" }
];

export const ORG_STATUS_OPTIONS = [
  { label: "待审核", value: 0 },
  { label: "已启用", value: 1 },
  { label: "已禁用", value: 2 }
];

export interface OrgAuditFilterParams {
  keyword?: string;
  org_type?: string;
  status?: number | string;
  region_id?: number | string;
  page?: number;
  page_size?: number;
}

export interface OrgAuditRegionInfo {
  id: number;
  name: string;
  code: string;
  path?: string;
}

export interface OrgAuditAssignment {
  owner_type: "inviter" | "region" | "service" | string;
  owner_ids?: number[];
  region_id?: number | null;
  fallback?: string | null;
}

export interface OrgAuditInviter {
  id: number;
  phone?: string;
  nickname?: string;
  real_name?: string;
}

export interface OrgAuditProfile {
  [key: string]: any;
}

export interface OrgAuditItem {
  audit_id: number;
  user_id: number;
  type: "company" | "individual";
  type_label: string;
  org_type: string;
  status: number;
  status_label: string;
  display_name: string;
  phone?: string;
  profile?: OrgAuditProfile | null;
  region?: OrgAuditRegionInfo | null;
  org?: { id: number | null; name: string | null } | null;
  assignment?: OrgAuditAssignment | null;
  invited_by?: number | null;
  inviter?: OrgAuditInviter | null;
  submitted_at?: string | null;
  verified_time?: string | null;
  company?: Record<string, any> | null;
  individual?: Record<string, any> | null;
}

export interface OrgAuditListResponse {
  list: OrgAuditItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
}

export type OrgAuditListResult = ApiResponse<OrgAuditListResponse>;

export interface LicenseOcrResult {
  company_name?: string;
  business_license_number?: string;
  legal_representative?: string;
  company_address?: string;
  business_scope?: string;
  established_date?: string;
  registered_capital?: string;
  raw?: Record<string, any>;
}

const toNumberArray = (values: any): number[] => {
  if (!values) return [];
  const arr = ensureArray(values);
  return arr
    .map(item => toNumber(item, NaN))
    .filter(item => !Number.isNaN(item) && item > 0);
};

const formatAssignment = (
  assignment: Record<string, any> | null | undefined
) => {
  if (!assignment || typeof assignment !== "object") {
    return null;
  }
  return {
    owner_type: assignment.owner_type ?? assignment.type ?? "",
    owner_ids: toNumberArray(assignment.owner_ids ?? assignment.candidates),
    region_id:
      assignment.region_id !== undefined && assignment.region_id !== null
        ? toNumber(assignment.region_id, 0) || null
        : null,
    fallback: assignment.fallback ?? null
  } as OrgAuditAssignment;
};

const formatInviter = (inviter: Record<string, any> | null | undefined) => {
  if (!inviter || typeof inviter !== "object") {
    return null;
  }
  const id = toNumber(inviter.id, 0);
  if (!id) return null;
  return {
    id,
    phone: inviter.phone ?? "",
    nickname: inviter.nickname ?? "",
    real_name: inviter.real_name ?? ""
  } as OrgAuditInviter;
};

const formatAuditItem = (item: Record<string, any>): OrgAuditItem => {
  const type = item.type === "individual" ? "individual" : "company";
  const region = item.region ?? null;
  return {
    audit_id: toNumber(item.audit_id ?? item.id, 0),
    user_id: toNumber(item.user_id, 0),
    type,
    type_label:
      item.type_label ?? (type === "company" ? "企业认证" : "个人认证"),
    org_type: item.org_type ?? (type === "company" ? "seller" : "buyer"),
    status: toNumber(item.status, 0),
    status_label: item.status_label ?? "",
    display_name: item.display_name ?? item.name ?? "",
    phone: item.phone ?? "",
    profile: item.profile ?? null,
    region: region
      ? {
          id: toNumber(region.id, 0),
          name: region.name ?? "",
          code: region.code ?? "",
          path: region.path ?? ""
        }
      : null,
    org: item.org
      ? {
          id:
            item.org.id !== undefined && item.org.id !== null
              ? toNumber(item.org.id, 0)
              : null,
          name: item.org.name ?? null
        }
      : null,
    assignment: formatAssignment(item.assignment),
    invited_by:
      item.invited_by !== undefined && item.invited_by !== null
        ? toNumber(item.invited_by, 0) || null
        : null,
    inviter: formatInviter(item.inviter),
    submitted_at: item.submitted_at ?? item.create_time ?? null,
    verified_time: item.verified_time ?? null,
    company: type === "company" ? (item.company ?? null) : null,
    individual: type === "individual" ? (item.individual ?? null) : null
  };
};

const mapListResponse = (
  response: OrgAuditListResult
): OrgAuditListResponse => {
  const payload = response.data ?? ({} as OrgAuditListResponse);
  const list = ensureArray<Record<string, any>>(payload.list ?? []).map(
    formatAuditItem
  );

  const rawPagination = payload.pagination ?? {};
  const pagination = normalisePagination(
    rawPagination,
    toNumber(
      (rawPagination as any).currentPage ?? (rawPagination as any).page,
      1
    ),
    toNumber((rawPagination as any).pageSize, list.length || 10),
    toNumber((rawPagination as any).total, list.length)
  );

  return {
    list,
    pagination
  };
};

const auditApi = {
  async fetchList(
    params: OrgAuditFilterParams & { page?: number; page_size?: number }
  ): Promise<OrgAuditListResponse> {
    const res = await http.request<OrgAuditListResult>(
      "get",
      "/system/org/audit",
      { params }
    );
    return mapListResponse(res);
  },

  approve(
    userId: number,
    type: "company" | "individual",
    payload: { remark?: string; region_id?: number | string } = {}
  ) {
    const data: Record<string, any> = { type };
    if (payload.remark) data.remark = payload.remark;
    if (payload.region_id !== undefined && payload.region_id !== null) {
      data.region_id = payload.region_id;
    }
    return http.request<ApiResponse<any>>(
      "post",
      `/system/org/audit/${userId}/approve`,
      {
        data
      }
    );
  },

  reject(userId: number, type: "company" | "individual", remark: string) {
    return http.request<ApiResponse<any>>(
      "post",
      `/system/org/audit/${userId}/reject`,
      {
        data: { type, remark }
      }
    );
  },

  recognizeLicense(imageUrl: string) {
    return http.request<ApiResponse<LicenseOcrResult>>(
      "post",
      "/auth/verification/license-ocr",
      {
        data: { image_url: imageUrl }
      }
    );
  },

  fastCreate(payload: Record<string, any>) {
    return http.request<ApiResponse<any>>(
      "post",
      "/system/org/audit/fast-create",
      {
        data: payload
      }
    );
  }
};

export default auditApi;
